<template>
  <div class="hotel-detail-container">
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    
    <div v-else-if="error" class="error-container">
      <el-empty :description="errorMessage">
        <template #extra>
          <el-button type="primary" @click="initData">重试</el-button>
          <el-button v-if="isNewHotelOwner" type="success" @click="openCreateHotelDrawer">创建酒店</el-button>
        </template>
      </el-empty>
    </div>
    
    <div v-else-if="hotelData" class="hotel-detail">
      <el-card class="hotel-card">
        <div class="hotel-header">
          <div class="hotel-info">
            <h1 class="hotel-name">{{ hotelData.hotelName }}</h1>
            <div class="hotel-meta">
              <span class="hotel-location">
                <el-icon><Location /></el-icon>
                {{ hotelData.country }} {{ hotelData.city }}
              </span>
              <div class="hotel-rating">
                <el-rate v-model="hotelData.rating" disabled show-score text-color="#ff9900" />
              </div>
            </div>
          </div>
          <div class="action-buttons">
            <el-button type="warning" @click="editHotel">编辑酒店信息</el-button>
          </div>
        </div>
        
        <el-divider />
        
        <div class="hotel-image-container">
          <div class="hotel-image">
            <img v-if="hotelData.imageUrl" :src="hotelData.imageUrl" :alt="hotelData.hotelName">
            <img v-else src="/src/assets/default.png" :alt="hotelData.hotelName">
          </div>
        </div>
        
        <el-divider />
        
        <div class="hotel-stats">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-statistic title="房间总数" :value="roomStats.total">
                <template #suffix>
                  <el-icon><House /></el-icon>
                </template>
              </el-statistic>
            </el-col>
            <el-col :span="8">
              <el-statistic title="可用房间" :value="roomStats.available" value-style="color: #3f8600">
                <template #suffix>
                  <el-icon><Check /></el-icon>
                </template>
              </el-statistic>
            </el-col>
            <el-col :span="8">
              <el-statistic title="订单总数" :value="orderStats.total">
                <template #suffix>
                  <el-icon><Document /></el-icon>
                </template>
              </el-statistic>
            </el-col>
          </el-row>
        </div>
        
        <el-divider />
        
        <div class="hotel-management">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-card class="management-card" @click="manageRooms">
                <el-icon class="card-icon"><House /></el-icon>
                <h3>房间管理</h3>
                <p>添加、编辑和管理酒店房间</p>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="management-card" @click="manageOrders">
                <el-icon class="card-icon"><Document /></el-icon>
                <h3>订单管理</h3>
                <p>查看和处理酒店订单</p>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="management-card" @click="manageReviews">
                <el-icon class="card-icon"><ChatLineRound /></el-icon>
                <h3>评价管理</h3>
                <p>查看客户评价</p>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>
    
    <create-hotel v-if="isNewHotelOwner" ref="createHotelRef" @refresh="initData"/>
    <update-hotel v-if="hotelData" ref="updateHotelRef" @refresh="initData"/>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { getHotelByUserId } from '@/api/hotel'
import { getRoomsByHotel } from '@/api/room'
import { useUserInfoStore } from '@/stores/userInfo'
import { ElMessage } from 'element-plus'
import { Location, House, Check, Document, ChatLineRound } from '@element-plus/icons-vue'
import CreateHotel from './components/CreateHotel.vue'
import UpdateHotel from './components/UpdateHotel.vue'

const router = useRouter()
const userInfoStore = useUserInfoStore()
const hotelData = ref(null)
const loading = ref(true)
const error = ref(false)
const errorMessage = ref('未找到酒店信息')
const createHotelRef = ref()
const updateHotelRef = ref()
const roomStats = ref({
  total: 0,
  available: 0
})
const orderStats = ref({
  total: 0,
  pending: 0
})

// 是否为新酒店商家（无关联酒店）
const isNewHotelOwner = computed(() => {
  return userInfoStore.isHotelOwner() && error.value && 
         errorMessage.value.includes('该用户不是酒店商家或无关联酒店')
})

// 初始化数据
const initData = async () => {
  if (!userInfoStore.userInfo || !userInfoStore.isHotelOwner()) {
    errorMessage.value = '您没有访问此页面的权限'
    error.value = true
    loading.value = false
    return
  }
  
  loading.value = true
  error.value = false
  
  try {
    // 获取当前用户的酒店信息
    const userId = userInfoStore.userInfo.user.userId
    const res = await getHotelByUserId(userId)
    const result = res.data
    
    if (result && result.code === 200 && result.data) {
      hotelData.value = result.data
      
      // 获取酒店房间统计
      await fetchRoomStats()
      
      // 获取订单统计（这里可以添加获取订单统计的逻辑）
      // 暂时使用模拟数据
      orderStats.value = {
        total: 10,
        pending: 2
      }
    } else {
      error.value = true
      errorMessage.value = result?.msg || '获取酒店信息失败'
    }
  } catch (err) {
    console.error('获取酒店信息错误:', err)
    error.value = true
    errorMessage.value = '网络错误，获取酒店信息失败'
  } finally {
    loading.value = false
  }
}

// 获取房间统计信息
const fetchRoomStats = async () => {
  if (!hotelData.value || !hotelData.value.hotelName) return
  
  try {
    const res = await getRoomsByHotel(hotelData.value.hotelName)
    const result = res.data
    
    if (result && result.code === 200 && Array.isArray(result.data)) {
      const rooms = result.data
      roomStats.value = {
        total: rooms.length,
        available: rooms.reduce((sum, room) => sum + (parseInt(room.availableCount) || 0), 0)
      }
    }
  } catch (err) {
    console.error('获取房间统计错误:', err)
  }
}

// 管理房间
const manageRooms = () => {
  if (!hotelData.value) return
  
  router.push({
    path: '/my-hotel/rooms'
  })
}

// 管理订单
const manageOrders = () => {
  if (!hotelData.value) return
  
  router.push({
    path: '/my-hotel/orders'
  })
}

// 管理评价
const manageReviews = () => {
  if (!hotelData.value) return
  
  router.push({
    path: '/my-hotel/reviews'
  })
}

// 编辑酒店信息
const editHotel = () => {
  if (!hotelData.value) return
  
  updateHotelRef.value.open(hotelData.value)
}

// 创建酒店
const openCreateHotelDrawer = () => {
  createHotelRef.value.open()
}

onMounted(() => {
  initData()
})
</script>

<style scoped>
.hotel-detail-container {
  padding: 20px;
}

.loading-container, .error-container {
  min-height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.hotel-card {
  min-height: 600px;
}

.hotel-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.hotel-name {
  font-size: 24px;
  margin: 0 0 10px;
}

.hotel-meta {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.hotel-location {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.hotel-image-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.hotel-image {
  width: 100%;
  max-width: 600px;
  height: 300px;
  overflow: hidden;
  border-radius: 8px;
}

.hotel-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.hotel-stats {
  margin: 20px 0;
}

.hotel-management {
  margin: 20px 0;
}

.management-card {
  height: 180px;
  text-align: center;
  cursor: pointer;
  transition: transform 0.3s;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.management-card:hover {
  transform: translateY(-5px);
}

.card-icon {
  font-size: 40px;
  margin-bottom: 10px;
  color: #409EFF;
}

.management-card h3 {
  margin: 10px 0;
  color: #303133;
}

.management-card p {
  color: #606266;
  margin: 0;
}
</style> 